#ifndef DATAPROVIDER_H
#define DATAPROVIDER_H

#include <QObject>
#include <QTimer>
#include <QQueue>
#include <QSoundEffect>
#include "networkmanager.h"
#include "localdb.h"
#include "shopinfo.h"
#include "material.h"
#include "record.h"
#include "printer.h"

const QString DB_PATH = "hyd.db";

class DataProvider : public QObject
{
    Q_OBJECT
public:
    static DataProvider* instance() {
        static DataProvider inst;
        return &inst;
    }

    void Login(QString tenant, QString username, QString password);
    ShopInfo* GetShopInfo(){
        return shop;
    };

    QStringList* GetMaterialTypes() {
        return &materialTypes;
    }

    //获取过滤后的物料模板列表
    QList<Material*> GetMaterials();

    //获取过滤后的物料模板列表
    QList<Record*> GetRecords();

    void SetSelectedMaterialType(const QString &t);
    void SetSelectedRecord(Record* r);

    void CreateRecordByMaterial(int MaterialId);
    void SplitRecord(Record* r);
    void DeleteRecord(QString id);
    void PrintRecord(Record& r);
    void SetShortName(QString c);

    void ChangePassword(QString oldPassword, QString newPassword);
    void DeleteAllExpiredRecords();

    bool UploadRecords();
    void ReadAndUploadRecords();
    bool NeedUpload();

private:
    explicit DataProvider(QObject *parent = nullptr);
    ~DataProvider();

    void downloadPrinterInfo();
    void downloadMerterialList();
    void downloadMaterialRecordList();

    void doWarning();

    QtPromise::QPromise<void> uploadRecords(QJsonArray list);
    QtPromise::QPromise<void> uploadChunk(const QJsonArray& chunk);

    Material* getMaterialById(int id);

private:
    NetworkManager netManager;
    LocalDb localDb;
    ShopInfo* shop;
    QList<Material*> materials;
    QStringList materialTypes;

    QList<Record*> records;
    // QMap<QString, Record*> updateRecordsMap;
    Printer printer;
    QTimer* timer;

    QString selectedMaterialType;
    Record* selectedRecord;

    QSoundEffect *effect;

    QString shortName;

signals:
    void proccessReady();
    void proccessFailed(const QString &error);

    void materialListUpdate();
    void recordListUpdate();
    void recordUpdate(Record* r);
    void tokenExpired(const QString &error);
};

#endif // DATAPROVIDER_H
